(function(){
	nsbase.views.userInfo = new UserInfoFunc();

	function UserInfoFunc () {
		
		var _self = this;

		_self.init = _init;

		var validations = nsbase.utility.validations,
			utilities = nsbase.utility,
        	clientResource = nsbase.resources.clientResource,
			regions = nsbase.config.region,
			userActions = nsbase.config.actionUrl.user;

		var cssClass = {
			selected:"selected",
			active:"active",
			failed:"failed",
			error:"error"
		};

		var $provice = $("#provice"),
			$city = $("#city");
		function _init () {
			initRegion();
			bindHandlers();
			bindPwdForm();
		}

		function bindHandlers () {
			$("#txtBrithday").datepicker({
				changeMonth: true,
				changeYear: true,
				maxDate:"-20y",
				dateFormat: "yy-mm-dd"
			});

			// edit user property
			$(".pro_area").click(function(){
				var sender = $(this);
				if(sender.hasClass(cssClass.active)) return;
				sender.tooltip();
				sender.addClass(cssClass.active);

				var editField = sender.attr("attr-field");
				var $showSpan = sender.find(".pro_show span"),
					originalValue = $showSpan.text();
				if(editField == "gender"){
					var sexValue = $showSpan.attr("field-value");
					bindSex(sexValue);
					return;
				}
				if(editField == "location"){
					var location = $showSpan.attr("field-value");
					var regionCodes = location.split(",");
					var provCode = regionCodes[0];
					if(provCode !== '0'){
						$provice.val(provCode);
					}
					bindCity(provCode,regionCodes[1]);
					return;
				}
				sender.find(".pro_edit input[type='text']").val(originalValue);
			});

			$(".pro_area input[type='text']").blur(function(){
				var sender = $(this);
				var value = sender.val();
				var $proArea = sender.parents(".pro_area:first");

				$proArea.removeClass(cssClass.failed).removeAttr("title");
				if(sender.hasClass("required") && validations.isNullOrWhiteSpace(value)){
					$proArea.attr("title",utilities.stringFormat(clientResource.msgNoEmpty,""));
					$proArea.addClass(cssClass.failed);
					return false;
				}

				if(sender.hasClass("digits") && !validations.intValidate(value)){
					$proArea.attr("title",clientResource.msgInvalidInt);
					$proArea.addClass(cssClass.failed);
					return false;
				}

				if(sender.hasClass("float") && !validations.floatValidate(value,1)){
					$proArea.attr("title",clientResource.msgInvalidFloat);
					$proArea.addClass(cssClass.failed);
					return false;
				}

			});

			// save user property
			$(".save").click(function (e) {
				e.stopPropagation();
				var sender = $(this);
				var $proArea = sender.parents(".pro_area:first");
				if($proArea.hasClass(cssClass.failed)) return false;

				var editValue;
				var editField = $proArea.attr("attr-field");
				if(editField == "gender"){
					editValue = $proArea.find(".pro_edit input:checked").val();
				} else if(editField == "location"){
					var region = getRegion();
					editValue = region.proviceCode + "," + region.cityCode;
				} else{
					editValue = $proArea.find(".pro_edit input[type='text']").val();
				}

				// 提交数据
				updateUserInfo($proArea,editField,editValue);
				$proArea.removeClass(cssClass.active);
			});
			$(".cancel").click(function (e) {
				e.stopPropagation();
				var sender = $(this);
				var $proArea = sender.parents(".pro_area:first");
				$proArea.tooltip("destroy");
				$proArea.removeClass(cssClass.active).removeClass(cssClass.failed).removeAttr("title");
			});

			$(".liHover").click(function(){
				var sender = $(this);
				var $proAuth = sender.parents(".pro_auth:first");
				$proAuth.find("li").removeClass(cssClass.selected);
				sender.addClass(cssClass.selected);
				var editField = $proAuth.attr("attr-field");
				var privacyEnum = nsbase.enums.userPrivacy.getEnumByKey(sender.attr("attr-privacy"));
				updateUserPrivacy($proAuth,editField,privacyEnum)
			});

			$(".btnIcon").click(function () {
				$(this).animate({"margin-top":-230});
			});
			
			$(".btnClose").click(function(){
				var $formContainer = $(this).parents(".pro_form");
				$formContainer.prev().animate({"margin-top":0});
				$formContainer.find("input").val("");
			});

			bindUpload();
		}

		function bindSex (sex) {
			$(".pro_edit input:radio[name='sex'][value='"+ sex +"']").prop("checked","checked");;
		}
		function getSexShow (sex) {
			return sex == "male" ? clientResource.lblMale : clientResource.lblFemale;
		}

		function getRegion(){
			var region ={
				proviceName:$provice.find("option:selected").text(),
				proviceCode:$provice.val(),
				cityName:$city.find("option:selected").text(),
				cityCode:$city.val()
			}
			return region;
		}
		function initRegion () {
			var $regionContainer = $(".pro_area[attr-field='location']");
			var locationCode = $regionContainer.find(".pro_show span").attr("field-value");
			var regionCodes = locationCode.split(",");
			var provCode = regionCodes[0];
			var cityCode = regionCodes[1];
			bindProvince(provCode);
			bindCity(provCode,cityCode);
			if(provCode !== '0'){
				$provice.val(provCode);
			}
			// 绑定页面展示
			var region = nsbase.ui.utility.getRegion(provCode,cityCode);
        	var loaction = region.provName + (region.cityName? " · " + region.cityName: "");
			$regionContainer.find(".pro_show span").text(loaction);

			$provice.change(function(){
				var provCode = $(this).val();
				bindCity(provCode);
			});
		}

		function bindProvince (provCode) {
			$provice.append('<option value="'+ regions.code0 +'">'+ regions.prov0 +'</option>');
			var provinces = regions.provinces.split(","),
				provCodes = regions.provcodes.split(",");
			for (var i = 0; i < provinces.length; i++) {
				$provice.append('<option value="'+ provCodes[i] +'">'+ provinces[i] +'</option>');
			}
			
		}
		function bindCity (provCode,cityCode) {
			if(provCode === '0') {
				$city.hide();
				return;
			}
			$city.empty();
			$city.show();
			if(!regions["prov"+provCode]) return;
			
			var cityCodes = regions["code"+ provCode].split(","),
        		cityNames = regions["prov"+ provCode].split(",");
        	for (var i = 0; i < cityNames.length; i++) {
				$city.append('<option value="'+ cityCodes[i] +'">'+ cityNames[i] +'</option>');
			}
			if(cityCode !== '0'){
				$city.val(cityCode);
			}
		}

		// 保存用户更新
		function updateUserInfo ($proContainer,field,fieldValue) {
			var param = {
				field:field,
				field_value:fieldValue
			};
			$proContainer.mask();
			nsbase.ajax.request(userActions.updateUserInfo, param, function(result) {
				$proContainer.unmask();
				if(result.success){
					var $showSpan = $proContainer.find(".pro_show span");
					var showValue = fieldValue;
					if(field == "gender"){
						$showSpan.attr("field-value",fieldValue);
						showValue = getSexShow(fieldValue);
					} else if(field == "location"){
						$showSpan.attr("field-value",fieldValue);
						var region = getRegion();
						showValue = region.proviceName + (region.cityName? " · " + region.cityName: "");
					} 
					$showSpan.text(showValue);
				}
			},function(){
				$proContainer.unmask();
			});
		}

		function updateUserPrivacy($proContainer,field,privacyEnum){
			var param = {
				field:field,
				field_value:privacyEnum.value
			};
			$proContainer.mask();
			nsbase.ajax.request(userActions.updateUserInfo, param, function(result) {
				$proContainer.unmask();
				if(result.success){
					$proContainer.find("li[attr-privacy='"+privacyEnum.key+"']").addClass(cssClass.selected);
				}
			},function(){
				$proContainer.unmask();
			});
		}
		function bindPwdForm () {
			var $formContainer = $("#pwdForm"),
				$btnSumbit = $formContainer.find(".btnSumbit"),
				$txtPwd = $formContainer.find(".txtPwd"),
				$txtNewPwd = $formContainer.find(".txtNewPwd"),
				$txtConfirmPwd = $formContainer.find(".txtConfirmPwd");


			$formContainer.find("input").blur(function(){
				var sender = $(this);
				inputEmptyValidate([sender]);

			});

			// validate password is match confirm password
			$txtNewPwd.blur(pwdValidate);
			$txtConfirmPwd.blur(pwdValidate);
			$btnSumbit.click(function () {
				inputEmptyValidate([$txtPwd,$txtNewPwd,$txtConfirmPwd]);
				if($formContainer.find("." + cssClass.error).length>0){
					return;
				}
				$formContainer.mask();
				var param = {
					original_pwd:$txtPwd.val(),
					new_pwd:$txtNewPwd.val()
				};
				nsbase.ajax.request(userActions.changePwd, param, function(result) {
					$formContainer.unmask();
					if(result.success){
						utilities.errorDialog(clientResource.msgPwdModifySuccess)
						$formContainer.find("input").val("");
						$formContainer.prev().animate({"margin-top":0});
					} else {
						utilities.errorDialog(result.message);
					}
				},function(){
					$formContainer.unmask();
				});
			});

			// validate input type = 'text' is empty or not
			function inputEmptyValidate(inputs) {
				$.each(inputs, function(i, item) {
					var labelDesc = nsbase.utility.trimEnd(item.prev().text(),'：'),
					msgSpan = item.parent().find("span:last");
					msgSpan.removeClass(cssClass.error).empty();

					if (validations.isNullOrWhiteSpace(item.val())) {
						msgSpan.addClass(cssClass.error).text(utilities.stringFormat(clientResource.msgNoEmpty, labelDesc));
					}
				});
			}

			function pwdValidate () {
				var sender = $(this),
					originalPwd = $txtPwd.val();
					pwd = $txtNewPwd.val(),
					confirmPwd = $txtConfirmPwd.val();
					msgSpan = $txtNewPwd.parent().find("span:last");
					confirmMsgSpan = $txtConfirmPwd.parent().find("span:last");
				if(!msgSpan.hasClass(cssClass.error)){
					if(originalPwd == pwd){
						msgSpan.addClass(cssClass.error).text(clientResource.msgSamePwd);
						$txtNewPwd.focus();
					}
					if (pwd.length > 0 && confirmPwd.length > 0) {
						if(pwd !== confirmPwd){
							confirmMsgSpan.addClass(cssClass.error).text(clientResource.msgNotMatchPwd);
						} else {
							confirmMsgSpan.removeClass(cssClass.error).empty();
						}
					} 
				}
			}
		}

		function bindUpload () {
			$("#btnUpload").fileupload({
		        url: userActions.imageUpload,
		        dataType: 'json',
		        // autoUpload: false,
		        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
		        maxFileSize: 1000000, //5000000, // 5 MB
		        // minFileSize:0,
		        messages:{
		        	acceptFileTypes: clientResource.uploadFileType,
	                maxFileSize: clientResource.uploadFileSize
		        },
		        processfail:function(e,data){
		        	if(data.files.error){
		        		utilities.errorDialog(data.files[0].error);
		        	}
		        },
		        done: function (e, data) {
		        	if(data.result.success){
		        		$(".u_photo").css("background-image","url('"+ data.result.data +"')");
		        	} else {
		        		utilities.errorDialog(data.result.message);
		        	}
		        },
		        fail:function(e,data){
					utilities.errorDialog(clientResource.msgUploadFail)
		        }
		    }).on("validate");
		}

	}
})();